package com.test.lab.validate;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex extends Rule{

    /**
     * 正则表达式
     */
    private Pattern pattern;

    public Regex(Pattern pattern) {
        setPattern(pattern);
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    /**
     * 判断某个字符串是符合某个正则表达式
     * @return true/false
     */
    @Override
    public boolean valid() {
        if (StringUtils.isNotBlank(this.getValue())) {
            if(null == this.pattern) {
                this.setMessage("格式不正确");
                return false;
            }
            Matcher matcher = this.pattern.matcher(this.getValue());
            if (!matcher.matches()) {
                this.setMessage("格式不正确");
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}
